export default {
  namespaced: true,
  state: () => ({
    // 存放购物车信息
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations: {
    // 添加商品到购物车
    addToCart(state, goods) {
      const findResult = state.cart.find(i => i.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveCartToStorage')
    },
    // 持久化保存数据
    saveCartToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 修改购物车商品勾选状态
    updateState(state, goods) {
      const res = state.cart.find(i => i.goods_id === goods.goods_id)
      if (res) {
        res.goods_state = goods.goods_state
        this.commit('m_cart/saveCartToStorage')
      }
    },
    // 修改购物车商品数量
    updateCount(state, goods) {
      const res = state.cart.find(i => i.goods_id === goods.goods_id)
      if (res) {
        res.goods_count = Number(goods.goods_count)
        this.commit('m_cart/saveCartToStorage')
      }
    },
    // 删除商品
    deleteGoodsById(state, goods_id) {
      state.cart = state.cart.filter(i => i.goods_id !== goods_id)
      this.commit('m_cart/saveCartToStorage')
    },
    // 修改所有商品状态
    updateAllGoodsState(state, newState) {
      state.cart.forEach(i => i.goods_state = newState)
      this.commit('m_cart/saveCartToStorage')
    },
    // 修改购物车商品
    updateCartMessage(state) {
      state.cart = state.cart.filter(i => !i.goods_state)
      this.commit('m_cart/saveCartToStorage')
    }
  },
  getters: {
    // 计算购物车商品总数
    total(state) {
      return state.cart.reduce((total, item) => total += item.goods_count, 0)
    },
    // 结算部分总数统计
    settleCount(state) {
      return state.cart.filter(i => i.goods_state).reduce((total, i) => total += i.goods_count, 0)
    },
    // 勾选商品总价
    checkedGoodsPrice(state) {
      return state.cart.filter(i => i.goods_state).reduce((total, i) => total += i.goods_count * i.goods_price, 0)
        .toFixed(2)
    }
  }
}
